import { Component, OnInit } from '@angular/core';
import { FormControl,FormGroup,FormBuilder, Validators } from '@angular/forms';
import { productService } from '../shared/product.service';
@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  //定义动态表单的模板数据结构
  searchForm:FormGroup;
  //产品的分类数据
  productCategory:string[];
  constructor(productSer:productService) {
    let fb = new FormBuilder();
    //初始化组件页面数据结构数组
    this.searchForm = fb.group({
      productName:['',[Validators.required,Validators.minLength(3)]],
      productPrice:[null,this.productPriceValidator],
      productCategory:['-1']
    })
    //获取产品的分类信息
    this.productCategory = productSer.getCategory();
  }

  ngOnInit() {}


  /**
   * @description 页面提交函数
   */
  onSearch(){
    if(this.searchForm.valid){
      console.log(this.searchForm.value)
    }
  }

  /**
   * @description 商品价格的验证函数
   * @param control 
   */
  productPriceValidator(control:FormControl):any{
    //值为空的时候返回null
    if(!control.value){
      return null;
    }
    let price = parseInt(control.value);
    console.log(price);
    if(price >= 0){
      return null;
    }else{
      return {productPrice:true};
    }
  }
}
